<template>
	<view class="groupRecord">
		<!-- 报餐统计 -->
		<view class="bctjheader">
			<view class="bctj linheight">
				<text class="t-icon t-icon-gaijiaofan text-icon"></text>
				<text class="tjtitle">团体报餐记录</text>
				<view class="tjtime">
					<picker mode="date" :value="dutyDates" fields="month" @change="onDateChange">
						<text>{{ dutyDates }}</text>
						<uni-icons type="down" size="20" color="#000"></uni-icons>
					</picker>
				</view>
			</view>
		</view>
		<view style="height: 100rpx;"></view>
		<!-- 列表 -->
		<view class="record" v-for="(item, index) in recordList" :key="index">
			<view class="bctj">
				<text class="tjtitle">{{ item.dutyDate }}</text>
				<view class="tools">
					<view class="btn bg-green" @click="editGroupRecord(item)">修改</view>
					<view class="btn bg-red" @click="delGroupRecord(item)">撤销</view>
				</view>
			</view>
			<!-- 餐数 -->
			<view class="bccs">
				<view class="sum">
					<view class="bold-num">{{ item.breakfastOrdered }}</view>
					<view>今日早餐</view>
				</view>
				<view class="sum">
					<view class="bold-num">{{ item.lunchOrdered }}</view>
					<view>今日中餐</view>
				</view>
				<view class="sum">
					<view class="bold-num">{{ item.dinnerOrdered }}</view>
					<view>今日晚餐</view>
				</view>
			</view>
		</view>

		<view class="toolbar-height"></view>
		<!-- 提交送样 -->
		<view class="toolbars">
			<view class="button-grounp">
				<view class="button payment-button" @tap="onChangeOrder()">
					立即报餐
				</view>
			</view>
		</view>

		<uni-popup ref="selectDialog" type="dialog" catchtouchmove="true">
			<uni-popup-dialog ref="selectClose" mode="base" :before-close="true" :title="title" @confirm="onOrderNow"
				@close="dialogSelectClose">
				<view class="groupform">
					<view class="groupitem">
						<label>报餐日期</label>
						<!-- <view class="groupinp">  :disabled="disabled"  -->
							<picker class="groupinp" mode="date" :start="dutyDate" :value="dutyDate" fields="day" @change="onDutyDateChange">
								<text>{{ dutyDate }}</text>
								<uni-icons type="down" size="20" color="#000" class="group-icons"></uni-icons>
							</picker>
						<!-- </view> -->
					</view>
					<view class="groupitem">
						<label>早餐数量</label>
						<input v-model="breakfastOrdered" type="number" placeholder="请输入早餐数量" class="groupinp" />
					</view>
					<view class="groupitem">
						<label>中餐数量</label>
						<input v-model="lunchOrdered" type="number" placeholder="请输入中餐数量" class="groupinp" />
					</view>
					<view class="groupitem">
						<label>晚餐数量</label>
						<input v-model="dinnerOrdered" type="number" placeholder="请输入晚餐数量" class="groupinp" />
					</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>

	</view>
</template>

<script>
	import {
		postTemporary,
		taskTemporary
	} from "@/proxy/food/food.api.js";
	// import {
	// 	getDates
	// } from "@/utils/dateTime";
	export default {
		async onLoad(option) {
			// 获取当前日期
			const { formattedDates,formattedDate } = this.setBuyDateTime();
			this.dutyDates = formattedDates;
			this.dutyDate = formattedDate;
			this.name = option.name;
			uni.setNavigationBarTitle({
				title: this.name
			});
			// console.log("参数", option)
			await this.postTemporaryData(); // 获取报餐记录列表
		},
		data() {
			return {
				breakfastOrdered:0, //早餐数量
				lunchOrdered:0, //中餐数量
				dinnerOrdered:0, //晚餐数量
				name: "", // 团体名称
				dutyDates: "", // 查询时间
				dutyDate: "", // 报餐时间
				title:"",
				// disabled:false,
				recordList: []
			}
		},
		methods: {
			async onDateChange(e) {
				this.dutyDates = e.detail.value;
				await this.postTemporaryData();
			},
			onDutyDateChange(e) {
				this.dutyDate = e.detail.value;
			},
			editGroupRecord(item){
				// this.disabled = true;
				this.title = "编辑团体报餐";
				// this.dutyDate = getDates();
				this.dutyDate = item.dutyDate;
				this.breakfastOrdered = item.breakfastOrdered;
				this.dinnerOrdered = item.dinnerOrdered;
				this.lunchOrdered = item.lunchOrdered;
				this.$refs.selectDialog.open();
			},
			async delGroupRecord(item){
				let that = this;
				const currentDate = new Date();
				const startOfDay = new Date(currentDate.setHours(0, 0, 0, 0)).getTime(); // 将时间设置为00:00
				// 获取 item.dutyDate 的时间戳
				const dutyDate = new Date(item.dutyDate);
				// 设置该日期的时间为当天的 5:00 AM
				// dutyDate.setHours(23, 59, 59, 59); // 设置时间为当天 17:00 AM
				const dutyDateTimestamp = dutyDate.getTime();
				
				// 判断是否是当天及之前的日期dutyDateTimestamp <= currentTimestamp
				if (dutyDateTimestamp <= startOfDay) {
					return this.$modal({
						title: '提示',
						content: `不能撤销 ${item.dutyDate} 的报餐`,
						showCancel: false, // 如果不需要取消按钮
						confirmText: '知道了'
					});
				}
				// 将 uni.showModal 封装为 Promise
				const confirmSubmit = () => {
					return new Promise((resolve, reject) => {
						uni.showModal({ // 弹框询问是否进行下一步事件
							title: '是否确认撤销？',
							success: function(res) {
								if (res.confirm) {
									resolve(); // 用户点击确认，继续执行提交操作
								} else if (res.cancel) {
									reject('用户取消提交'); // 用户点击取消，返回失败
								}
							}
						});
					});
				};
				
				try {
					// 等待用户确认
					await confirmSubmit();
				
					// 用户点击确认后执行的异步操作
					const result = await taskTemporary({
						name: this.name,
						dutyDate: item.dutyDate,
						breakfastOrdered: "",
						lunchOrdered: "",
						dinnerOrdered: "",
					});			
				
					if (result.code == 200) {
						console.log("是否撤销成功", result);
						// 提交成功后的操作
						that.$toast({
							title: "撤销成功",
							icon: "success",
							success: () => {
								var nav = setTimeout(() => {
									that.postTemporaryData();
									clearTimeout(nav)
								}, 500)
							}
						});
					} else {
						that.$toast({
							title: result.data.msg,
						});
					}
				
				} catch (err) {
					// 捕获用户取消或者提交失败的错误
					if (err === '用户取消提交') {
						console.log('用户取消提交');
					} else {
						that.$toast({
							icon: 'none',
							title: '提交失败',
							duration: 2000
						});
						console.log(err);
					}
				}
				
			},
			onChangeOrder() {
				this.disabled = false;
				this.title = "开始团体报餐";
				this.dutyDate = this.dutyDate;
				this.breakfastOrdered = "";
				this.dinnerOrdered = "";
				this.lunchOrdered = "";
				this.$refs.selectDialog.open();
			},
			isTodayAndAfter(key, inputDate) {
			    // 获取当前日期和时间
			    const now = new Date();
			    
			    // 获取传入的日期，假设格式是 'YYYY-MM-DD'
			    const input = new Date(inputDate);
			
			    // 比较日期部分（不考虑时间部分），判断是否是今天
			    const isToday = now.getFullYear() === input.getFullYear() &&
			                    now.getMonth() === input.getMonth() &&
			                    now.getDate() === input.getDate();	
			    // 获取当前的时间，判断是否超过
			    const hours = now.getHours();
			    const minutes = now.getMinutes();
			    let isAfter = false;
			    switch (key) {
			        case "breakfastOrdered":
			            // 判断是否已过08:30
			            // isAfter = (hours > 8) || (hours === 8 && minutes >= 30);
						isAfter = isToday;
			            break;
			        case "lunchOrdered":
			            // 判断是否已过12:00
			            isAfter = (hours > 9) || (hours === 9 && minutes >= 0);
			            break;
			        case "dinnerOrdered":
			            // 判断是否已过18:00
			            isAfter = (hours > 15) || (hours === 15 && minutes >= 0);
			            break;
			    }
			    
			    // 返回是否是今天且是否超过指定时间
			    return isToday && isAfter;
			},
			// 校验是否为空的方法
			isEmpty(value) {
				return value == null || value == undefined || value == '' || value == 0 || value == '0';
			},
			// 提交报餐
			async onOrderNow() {
				if (this.isEmpty(this.name)) {
					return this.$toast({
						title: "请选择报餐部门",
						icon: "error",
					});
				}
				
				const currentDate = new Date();
				const startOfDay = new Date(currentDate.setHours(0, 0, 0, 0)).getTime(); // 将时间设置为00:00
				// 获取 item.dutyDate 的时间戳
				const dutyDate = new Date(this.dutyDate);
				// 设置该日期的时间为当天的 5:00 AM
				// dutyDate.setHours(23, 59, 59, 59); // 设置时间为当天 17:00 AM
				const dutyDateTimestamp = dutyDate.getTime();
				
				// 判断是否是当天及之前的日期dutyDateTimestamp <= currentTimestamp
				if (dutyDateTimestamp <= startOfDay) {
					return this.$modal({
						title: '提示',
						content: `不能修改 ${this.dutyDate} 的报餐`,
						showCancel: false, // 如果不需要取消按钮
						confirmText: '知道了'
					});
				}
				
				if (this.isEmpty(this.breakfastOrdered) && this.isEmpty(this.lunchOrdered) && this.isEmpty(this.dinnerOrdered)) {
					return this.$toast({
						title: "数量不能为空",
						icon: "error",
					});
				}
				
				if ((this.breakfastOrdered !== 0 && this.breakfastOrdered !== "0") && (this.breakfastOrdered)) {
					let result = this.isTodayAndAfter("breakfastOrdered",this.dutyDate);
					if (result) {
					    // console.log("传入日期是今天，并且已经过了08:30");
						return this.$modal({
							title: '提示',
							content: `早餐已到当天，不可再订`,
							showCancel: false, // 如果不需要取消按钮
							confirmText: '知道了'
						});
					}
				}
				
				if (this.lunchOrdered !== 0 && this.lunchOrdered !== "0"  && (this.lunchOrdered)){
					let result = this.isTodayAndAfter("lunchOrdered",this.dutyDate);
					if (result) {
						// console.log("传入日期是今天，并且已经过了12:00");
						return this.$modal({
							title: '提示',
							content: `中餐已过9:00，不可再订`,
							showCancel: false, // 如果不需要取消按钮
							confirmText: '知道了'
						});
					}
				}
				
				if (this.dinnerOrdered !== 0 && this.dinnerOrdered !== "0"  && (this.dinnerOrdered)){
					let result = this.isTodayAndAfter("dinnerOrdered",this.dutyDate);
					if (result) {
					    // console.log("传入日期是今天，并且已经过了18:00");
						return this.$modal({
							title: '提示',
							content: `晚餐已过15:00，不可再订`,
							showCancel: false, // 如果不需要取消按钮
							confirmText: '知道了'
						});
					}
				}  
				
				try {
					// 用户点击确认后执行的异步操作
					const result = await taskTemporary({
						name: this.name,
						dutyDate: this.dutyDate,
						breakfastOrdered: this.breakfastOrdered,
						lunchOrdered: this.lunchOrdered,
						dinnerOrdered: this.dinnerOrdered,
					});
					if (result.code == 200) {
						const { formattedDate } = this.setBuyDateTime();
						this.dutyDate = formattedDate;
						this.breakfastOrdered = "";
						this.dinnerOrdered = "";
						this.lunchOrdered = "";
						console.log("报餐是否成功", result);
						this.postTemporaryData();
						this.$refs.selectDialog.close();
					} else {
						this.$toast({
							title: result.data.msg,
						});
					}
				
				} catch (err) {
					this.$toast({
						icon: 'none',
						title: '发起失败，请联系管理员！',
						duration: 2000
					});
					console.log(err);
				}
				
			},
			setBuyDateTime(){
				const currentDate = new Date();
				const year = currentDate.getFullYear();
				const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // getMonth() 返回的是0-11，所以加1
				const day = String(currentDate.getDate()).padStart(2, '0'); // getDate() 返回 1-31，处理成两位格式
				const formattedDates = `${year}-${month}`;
				const formattedDate = `${year}-${month}-${day}`;
				return {
					formattedDates,
					formattedDate,
				}
			},
			dialogSelectClose() {
				const { formattedDate } = this.setBuyDateTime();
				this.dutyDate = formattedDate;
				this.$refs.selectDialog.close();
			},
			async postTemporaryData() {
				try {
					// 用户点击确认后执行的异步操作
					const result = await postTemporary({
						name: this.name,
						duty: this.dutyDates,
					});
					if (result.code == 200) {
						this.recordList = result.data;
						console.log("报餐部门记录", result);
					} else {
						this.$toast({
							title: result.data.msg,
						});
					}

				} catch (err) {
					this.$toast({
						icon: 'none',
						title: '发起失败，请联系管理员！',
						duration: 2000
					});
					console.log(err);
				}
			},
		}
	}
</script>

<style lang="scss">
	/* app端 */
	/* #ifdef APP-PLUS || H5 */
	#app,
	/* #endif */
	page {
		background-color: #F3F4F6;
		height: 100%;
	}

	.uni-dialog-title {
		padding-top: 10rpx !important;
	}

	.uni-popup-dialog {
		padding: 20rpx !important;
	}

	.uni-dialog-content {
		display: unset !important;
	}

	.groupRecord {
		margin: 0 20rpx;

		.bctjheader {
			position: fixed;
			top: 0;
			left: 20rpx;
			right: 20rpx;
			z-index: 99;
		}

		.linheight {
			line-height: 60rpx;
		}

		// width: 100% !important;
		.bctj {
			display: flex;
			align-items: center;
			padding: 20rpx 20rpx;
			position: relative;
			// margin-bottom: 20rpx;
			background-color: #FFF;


			.text-icon {
				width: 44rpx;
				height: 44rpx;
			}

			.tjtitle {
				flex: 1;
				font-size: 30rpx;
				color: #303133;
				margin-right: 10rpx;
				margin-left: 15rpx;
			}

			.tjtime {
				align-self: center;
				font-size: 30rpx;
				// color: #606266;
				margin-left: 10rpx;
			}

			&::after {
				position: absolute;
				z-index: 3;
				left: 0;
				right: 0;
				height: 0;
				content: '';
				bottom: 0;
				-webkit-transform: scaleY(0.5);
				transform: scaleY(0.5);
				border-bottom: 1px solid #E4E7ED;
				border-bottom-width: 1px;
				border-bottom-style: solid;
				border-bottom-color: rgb(228, 231, 237);
			}
		}

		.bccs {
			justify-content: space-around;
			display: flex;
			align-content: center;
			background: #fff;
			// border-radius: 10rpx;
			margin-bottom: 20rpx;

			.sum {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				flex: 1;
				margin: 30rpx 0;
				font-size: small;
				color: #75787d;

				.bold-num {
					font-weight: bold;
					font-size: 40rpx;
				}
			}
		}

		.bccp {
			// margin: 20rpx;
			// border-radius: 20rpx;
			background-color: #ffffff;
			padding: 20rpx 30rpx;

			.cptitle {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 30rpx;
			}

			.file-picker__box {
				width: 100% !important;
				height: 650rpx !important;
			}
		}

		.record {
			margin: 20rpx 0;

			.tools {
				display: flex;
				font-size: 28rpx;

				.btn {
					display: flex;
					align-items: center;
					justify-content: center;
					// width: 120rpx;
					padding: 8rpx 16rpx;
					color: #fff;
					border-radius: 10rpx;
					margin-left: 10rpx;
				}

				.bg-red {
					background-color: #FF0000;
				}

				.bg-green {
					background-color: #2ecc71;
				}
			}
		}
	}

	.groupform {
		font-size: 30rpx;
		.groupitem{
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
			.groupinp {
				height: 75rpx;
				line-height: 75rpx;
				padding-left: 20rpx;
				border: 1rpx solid #eee;
				margin-left: 20rpx;
				border-radius: 10rpx;
				flex:1;
				.group-icons{
					float: right;
				}
			}
		}
		
	}

	// 吸底工具栏
	.toolbars {
		position: fixed;
		left: 0;
		right: 0;
		bottom: var(--window-bottom);
		z-index: 999999;
		height: 100rpx;
		display: flex;
		padding: 0 15rpx;
		align-items: center;
		border-top: 1rpx solid #ededed;
		border-bottom: 1rpx solid #ededed;
		background-color: #fff;
		box-sizing: content-box;

		.button-grounp {
			margin-left: auto;
			display: flex;
			justify-content: space-between;
			text-align: center;
			line-height: 72rpx;
			font-size: 13px;
			color: #fff;

			.button {
				width: 200rpx;
				margin: 0 10rpx;
				border-radius: 72rpx;
			}

			.payment-button {
				background-color: #0081ff;

				&.disabled {
					opacity: 0.6;
				}
			}
		}
	}

	// 底部占位空盒子
	.toolbar-height {
		height: 120rpx;
	}
</style>